[% setvar title Exegesis 5: Pattern Matching %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Exegesis 5: Pattern Matching</p>
<a name='AUTHOR'></a><h1>AUTHOR</h1>
<p>Damian Conway &lt;<a href='mailto:damian@conway.org'>damian@conway.org</a>&gt;</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Larry Wall &lt;<a href='mailto:larry@wall.org'>larry@wall.org</a>&gt;
  Date: 22 Aug 2002
  Last Modified: 1 Jan 2010
  Number: 5
  Version: 3</pre>
<p>[Update: Please note that this was written several years ago, and
a number of things have changed since then.  Rather than changing
the original document, we'll be inserting &quot;Update&quot; notes like this
one to tell you where the design has since evolved.  (For the better,
we hope).  In any event, for the latest Perl 6 design (or to figure out
any cryptic remarks below) you should read the Synopses, which are kept
very much more up-to-date than either the Apocalypses or Exegeses.]</p>
<ul>
<li><a name='Come gather round Mongers, whatever you code'></a><i>Come gather round Mongers, whatever you code</i></li>
<li><a name='And admit that your forehead's about to explode'></a><i>And admit that your forehead's about to explode</i></li>
<li><a name=''Cos Perl patterns induce complete brain overload'></a><i>'Cos Perl patterns induce complete brain overload</i></li>
<li><a name='If there's source code you should be maintainin''></a><i>If there's source code you should be maintainin'</i></li>
<li><a name='Then you better start learnin' Perl 6 patterns soon'></a><i>Then you better start learnin' Perl 6 patterns soon</i></li>
<li><a name='For the regexes, they are a-changin''></a><i>For the regexes, they are a-changin'</i></li>
<ul>
<li><a name='-- Bob Dylan, &quot;The regexes they are a-changin'&quot; (Perl 6 remix)'></a>-- Bob Dylan, &quot;The regexes they are a-changin'&quot; (Perl 6 remix)</li>
</ul>
</ul>
<p>Apocalyse 5 marks a significant departure in the on-going design of Perl 6.</p>
<p>Previous Apocalypses took an evolutionary approach to changing Perl's
general syntax, data structures, control mechanisms, and operators. New
features were added, old features removed, existing features were
enhanced, extended, and simplified. But the changes described were
remedial, not radical.</p>
<p>Larry could have taken the same approach with regular expressions. He could
have tweaked some of the syntax, added new <code>(?...)</code> constructs, cleaned
up the rougher edges, and moved on.</p>
<p>Fortunately, however, he's taking a much broader view of Perl's future
than that. And he saw that the problem with regular expressions was <i>not</i>
that they lacked a <code>(?$var:...)</code> extension to do named captures, or
that they needed a <code>\R</code> metatoken to denote a recursive subpattern,
or that there was a <code>[:YourNamedCharClassHere:]</code> mechanism missing.</p>
<p>He saw that those features, laudable as they were individually, would
just compound the real problem. Which was that Perl 5
regular expressions were already groaning under the accumulated weight
of their own metasyntax. And that a decade of accretion had left the
once-clean notation arcane, baroque, inconsistent, and obscure.</p>
<p>It was time to throw away the prototype.</p>
<p>Even more importantly, as powerful as Perl 5 regexes are, they are not nearly
powerful enough. Modern text manipulation is predominantly about processing
structured, hierarchical text. And that's just plain painful with regular
expressions. The advent of modules like Parse::Yapp and Parse::RecDescent
reflects the community's widespread need for more sophisticated parsing
mechanisms. Mechanisms that should be native to Perl.</p>
<p>As Piers Cawley has so eloquently misquoted: <i>&quot;It is a truth universally
acknowledged that any language in possession of a rich syntax must be in
want of a rewrite.&quot;</i> Perl regexes are such a language. And Apocalypse 5
is precisely that rewrite.</p>
<a name='What's the diff?'></a><h1>What's the diff?</h1>
<p>So let's take a look at some of those new features. To do that, we'll
consider a series of examples structured around a common theme:
recognizing and manipulating data in the Unix
<a href='http://www.gnu.org/manual/diffutils-2.8.1/html_node/Detailed-Normal.html' target='_blank'>www.gnu.org</a></p>
<p>A classic diff consists of zero-or-more text transformations, each of
which is known as a &quot;hunk&quot;. A hunk consists of a modification specifier,
followed by one or more lines of context. Each hunk is either an append,
a delete, or a change, and the type of hunk is specified by a single
letter (<code>'a'</code>, <code>'d'</code>, or <code>'c'</code>). Each of these single-letter specifiers is
prefixed by the line numbers of the lines in the original document it
affects, and followed by the equivalent line numbers in the transformed
file. The context information consists of the lines of the original file
(each preceded by a <code>'&lt;'</code> character), then the lines of the
transformed file (each preceded by a <code>'&gt;'</code>). Deletes omit the
transformed context, appends omit the original context. If both contexts
appear, they are separated by a line consisting of three hyphens.</p>
<p>Phew! You can see why natural language isn't the preferred way of
specifying data formats.</p>
<p>The preferred way is, of course, to specify such formats as patterns.
And, indeed, we could easily throw together a few Perl 6 patterns that
collectively would match any data conforming to that format:</p>
<pre>    $file = rx/ ^  &lt;$hunk&gt;*  $ /;

    $hunk = rx :i { 
        [ &lt;$linenum&gt; a :: &lt;$linerange&gt; \n
          &lt;$appendline&gt;+ 
        |
          &lt;$linerange&gt; d :: &lt;$linenum&gt; \n
          &lt;$deleteline&gt;+
        |
          &lt;$linerange&gt; c :: &lt;$linerange&gt; \n
          &lt;$deleteline&gt;+
          --- \n
          &lt;$appendline&gt;+
        ]
      |
        (\N*) ::: { fail &quot;Invalid diff hunk: $1&quot; }</pre>
<p>[Update: Backrefs are now numbered starting at 0.]</p>
<pre>    };

    $linerange = rx/ &lt;$linenum&gt; , &lt;$linenum&gt;
                   | &lt;$linenum&gt;
                   /;

    $linenum = rx/ \d+ /;

    $deleteline = rx/^^ \&lt; &lt;sp&gt; (\N* \n) /;
    $appendline = rx/^^ \&gt; &lt;sp&gt; (\N* \n) /;

    # and later...

    my $text is from($*ARGS);

    print &quot;Valid diff&quot; 
        if $text =~ /&lt;$file&gt;/;</pre>
<a name='Starting gently'></a><h1>Starting gently</h1>
<p>There's a lot of new syntax there, so let's step through it slowly,
starting with:</p>
<pre>    $file = rx/ ^  &lt;$hunk&gt;*  $ /;</pre>
<p>This statement creates a pattern object. Or, as it's known in Perl 6, a
&quot;rule&quot;. People will probably still call them &quot;regular expressions&quot; or
&quot;regexes&quot; too (and the keyword <code>rx</code> reflects that), but Perl patterns
long ago ceased being anything like &quot;regular&quot;, so we'll try and avoid
those terms.</p>
<p>[Update: We've resurrected the term &quot;regex&quot; to refer to these patterns
in general.  When we say &quot;rule&quot; now, we're specifically referring to the
kind of regex that you would use in a grammar.  See S05.]</p>
<p>In any case, the <code>rx</code> constructor builds a new rule, which is then
stored in the <code>$file</code> variable.  The Perl 5 equivalent would be:</p>
<pre>    # Perl 5
    my $file = qr/ ^  (??{$hunk})*  $ /x;</pre>
<p>Which illustrates quite nicely why the entire syntax
needed to change.</p>
<p>The name of the rule constructor has changed from <code>qr</code> to <code>rx</code>,
because in Perl 6 rule constructors <i>aren't</i> quotelike contexts.
In particular, variables don't interpolate into <code>rx</code> constructors
in the way they do for a <code>qq</code> or a <code>qx</code>. That's why we can embed the
<code>$hunk</code> variable before it's actually initialized.</p>
<p>In Perl 6, an embedded variable becomes part of the rule's implementation
rather than part of its &quot;source code&quot;. As we'll see shortly, the pattern
itself can determine how the variable is treated (i.e. whether to
interpolate it literally, or treat it as a subpattern, or use it as a
container).</p>
<a name='Lay it out for me'></a><h1>Lay it out for me</h1>
<p>In Perl 6 every rule implicitly has the equivalent of the Perl 5 <code>/x</code> modifier
turned on, so we could lay out (and annotate) that first pattern like this:</p>
<pre>    $file = rx/ ^               # Must be at start of string
                &lt;$hunk&gt;         # Match what the rule in $hunk would match...
                        *       #          ...zero-or-more times
                $               # Must be at end of string (no newline allowed)
              /;</pre>
<p>Because <code>/x</code> is the default, the whitespace in the pattern is ignored,
which allows us to lay the rule out more readably. Comments are also honoured,
which enables us to document the rule sensibly. You can even use the closing
delimiter in a comment safely:</p>
<pre>    $caveat = rx/ Make \s+ sure \s+ to \s+ ask
                  \s+ (mum|mom)                 # handle UK/US spelling
                  \s+ (and|or)                  # handle and/or
                  \s+ dad \s+ first
                /;</pre>
<p>Of course, the examples in this Exegesis <i>don't</i> represent good
comments in general, since they document what is happening,
rather than why.</p>
<p>The meanings of the <code>^</code> and <code>*</code> metacharacters are unchanged
from Perl 5. However, the meaning of the <code>$</code> metacharacter <i>has</i>
changed slightly: it no longer allows an optional newline before the end
of the string. If you want that behaviour, you need to specify it
explicitly. For example, to match a line ending in digits: <code>/ \d+ \n? $/</code></p>
<p>The compensation is that, in Perl 6, a <code>\n</code> in a pattern matches a <i>logical</i>
newline (that is any of: <code>&quot;\015\012&quot;</code> or <code>&quot;\012&quot;</code> or <code>&quot;\015&quot;</code>
or <code>&quot;\x85&quot;</code> or <code>&quot;\x2028&quot;</code>), rather than just a
<i>physical</i> ASCII newline (i.e. just <code>&quot;\012&quot;</code>). And a <code>\n</code> will always
try to match any kind of physical newline marker (not just the current system's
favorite), so it correctly matches against strings that have been
aggregrated from multiple systems.</p>
<a name='Interpolate ye not...'></a><h1>Interpolate ye not...</h1>
<p>The really new bit in the <code>$file</code> rule is the <code>&lt;$hunk&gt;</code> element.
It's a directive to grab whatever's in the <code>$hunk</code> variable (presumably
another pattern) and attempt to match it at that point in the rule. The
important point is that the contents of <code>$hunk</code> are only grabbed when
the pattern matching mechanism actually needs to match against them,
<i>not</i> when the rule is being constructed. So it's like the mysterious
<code>(??{...})</code> construct in Perl 5 regexes.</p>
<p>The angle brackets themselves are a much more general mechanism in Perl 6 rules.
They are the &quot;metasyntactic markers&quot; and replace the Perl 5 <code>(?...)</code> syntax.
They are used to specify numerous other features of Perl 6 rules, many of which
we will explore below.</p>
<p>Note that if we <i>hadn't</i> put the variable in angle-brackets, and had
just written:</p>
<pre>        rx/ ^  $hunk*  $ /;</pre>
<p>then the contents of <code>$hunk</code> would <i>still</i> not be interpolated when
the pattern was parsed. Once again, the pattern would grab the
contents of the variable when it reached that point in its match.
But, this time, without the angle brackets around <code>$hunk</code>, the
pattern would try to match the contents of the variable as an
atomic literal string (rather than as a subpattern). &quot;Atomic&quot;
means that the <code>*</code> repetition quantifier applies to everything
that's in <code>$hunk</code>, <i>not</i> just to the last character
(as it does in Perl 5).</p>
<p>In other words, a raw variable in a Perl 6 pattern is matched
as if it was a Perl 5 regex in which the interpolation had been
<code>quotemeta</code>'d and then placed in a pair of non-capturing parentheses.
That's really handy in something like:</p>
<pre>        # Perl 6
        my $target = &lt;&gt;;                  # Get literal string to search for
        $text =~ m/ $target* /;           # Search for them as literals</pre>
<p>[Update: <code>&lt;&gt;</code> is no longer the input operator.  And <code>=~</code> has been
replaced by <code>~~</code>.]</p>
<p>which in Perl 5 we'd have to write as:</p>
<pre>        # Perl 5
        my $target = &lt;&gt;;                  # Get literal string to search for
        chomp $target;                    # No autochomping in Perl 5 
        $text =~ m/ (?:\Q$target\E)* /x;  # Search for it, quoting metas</pre>
<p>Raw arrays and hashes interpolate as literals too. For example, if we
use an array in a Perl 6 pattern, the matcher will attempt to match any
of its elements (each as a literal). So:</p>
<pre>        # Perl 6
        @cmd = ('get','put','try','find','copy','fold','spindle','mutilate');

        $str =~ / @cmd \( .*? \) /;     # Match a cmd, followed by stuff in parens</pre>
<p>is the same as:</p>
<pre>        # Perl 5 
        @cmd = ('get','put','try','find','copy','fold','spindle','mutilate');
        $cmd = join '|', map { quotemeta $_ } @cmd;

        $str =~ / (?:$cmd) \( .*? \) /;</pre>
<p>By the way, putting the array into angle brackets would cause the matcher to
try and match each of the array elements as a pattern, rather than as a literal.</p>
<a name='The incredible $hunk'></a><h1>The incredible <code>$hunk</code></h1>
<p>The rule that <code>&lt;$hunk&gt;</code> tries to match against is the next one defined
in the program. Here's the annotated version of it:</p>
<pre>    $hunk = rx :i {                             # Case-insensitively...
        [                                       #   Start a non-capturing group
            &lt;$linenum&gt;                          #     Match the subrule in $linenum
            a                                   #     Match a literal 'a'
            ::                                  #     Commit to this alternative
            &lt;$linerange&gt;                        #     Match the subrule in $linerange
            \n                                  #     Match a newline
            &lt;$appendline&gt;                       #     Match the subrule in $appendline...
                          +                     #         ...one-or-more times
        |                                       #   Or...
          &lt;$linerange&gt; d :: &lt;$linenum&gt; \n       #     Match $linerange, 'd', $linenum, newline
          &lt;$deleteline&gt;+                        #     Then match $deleteline once-or-more
        |                                       #   Or...
          &lt;$linerange&gt; c :: &lt;$linerange&gt; \n     #     Match $linerange, 'c', $linerange, newline
          &lt;$deleteline&gt;+                        #     Then match $deleteline once-or-more
          --- \n                                #     Then match three '-' and a newline
          &lt;$appendline&gt;+                        #     Then match $appendline once-or-more
        ]                                       #   End of non-capturing group
      |                                         # Or...
        (                                       #   Start a capturing group
            \N*                                 #     Match zero-or-more non-newlines
        )                                       #     End of capturing group
        :::                                     #     Emphatically commit to this alternative
        { fail &quot;Invalid diff hunk: $1&quot; }        #     Then fail with an error msg
    };</pre>
<p>The first thing to note is that, like a Perl 5 <code>qr</code>, a Perl 6 <code>rx</code> can take
(almost) any delimiters we choose. The <code>$hunk</code> pattern uses <code>{...}</code>, but
we could have used:</p>
<pre>        rx/pattern/     # Standard
        rx[pattern]     # Alternative bracket-delimiter style
        rx&lt;pattern&gt;     # Alternative bracket-delimiter style
        rxE&lt;laquo&gt;formeE&lt;raquo&gt;      # D&lt;eacute&gt;limiteurs trE&lt;egrave&gt;s chic
        rx&gt;pattern&lt;     # Inverted bracketing is allowed too (!)</pre>
<p>[Update: Inverted brackets are no longer allowed.]</p>
<pre>        rxE&lt;raquo&gt;MusterE&lt;laquo&gt;      # AnfE&lt;uuml&gt;hrungszeichen in richtiger Reihenfolge
        rx!pattern!     # Excited
        rx=pattern=     # Unusual
        rx?pattern?     # No special meaning in Perl 6
        rx#pattern#     # Careful with these: they disable internal comments</pre>
<p>[Update: <code>#</code> is no longer allowed as the delimiter in any quote-like
construct.  It is always a comment.  This is not a hardship in Perl 6--you
have plenty of Unicode characters to choose from.]</p>
<a name='Modified modifiers'></a><h1>Modified modifiers</h1>
<p>In fact, the only characters not permitted as <code>rx</code> delimiters are
<code>':'</code> and <code>'('</code>. That's because <code>':'</code> is the character used to
introduce pattern modifiers in Perl 6, and <code>'('</code> is the character used
to delimit any arguments that might be passed to those pattern modifiers.</p>
<p>[Update: <code>:</code> and <code>#</code> are never permitted, but <code>(</code> is now permitted
if there is whitespace before it.]</p>
<p>In Perl 6 pattern modifiers are placed <i>before</i> the pattern, rather
than after it. That makes life easier for the parser, since it doesn't
have to go back and reinterpret the contents of a rule when it reaches
the end and discovers a <code>/s</code> or <code>/m</code> or <code>/i</code> or <code>/x</code>. And it makes life
easier for anyone reading the code...for precisely the same reason.</p>
<p>The only modifier used in the <code>$hunk</code> rule is the <code>:i</code> (case-insensitivity)
modifier, which works exactly as it does in Perl 5.</p>
<p>The other rule modifiers available in Perl 6 are:</p>
<ul>
<li><a name=':e or :each'></a><code>:e</code> or <code>:each</code></li>
<p>This is the replacement for Perl 5's <code>/g</code> modifier. It causes a
match (or substitution) to be attempted as many times as possible.
The name was changed because &quot;each&quot; is shorter and clearer in intent
than &quot;globally&quot;. And because the <code>:each</code> modifier can be combined with
other modifiers (see below) in such a way that it's no longer &quot;global&quot;
in its effect.</p>
<p>[Update: Switched back to <code>:g</code> now.]</p>
<li><a name=':x($count)'></a><code>:x($count)</code></li>
<p>This modifier is like <code>:e</code>, in that it causes the match or substitution
to be attempted repeatedly. However, unlike <code>:e</code>, it specifies exactly
how many times the match must succeed. For example:</p>
<pre>        &quot;fee fi &quot;       =~ m:x(3)/ (f\w+) /;  # fails
        &quot;fee fi fo&quot;     =~ m:x(3)/ (f\w+) /;  # succeeds (matches &quot;fee&quot;,&quot;fi&quot;,&quot;fo&quot;)
        &quot;fee fi fo fum&quot; =~ m:x(3)/ (f\w+) /;  # succeeds (matches &quot;fee&quot;,&quot;fi&quot;,&quot;fo&quot;)</pre>
<p>Note that the repetition count doesn't have to be a constant:</p>
<pre>        m:x($repetitions)/ pattern /</pre>
<p>There is also a series of tidy abbreviations for all the constant cases:</p>
<pre>        m:1x/ pattern /         # same as: m:x(1)/ pattern /
        m:2x/ pattern /         # same as: m:x(2)/ pattern /
        m:3x/ pattern /         # same as: m:x(3)/ pattern /
        # etc.</pre>
<li><a name=':nth($count)'></a><code>:nth($count)</code></li>
<p>This modifier causes a match or substitution to be attempted repeatedly,
but to ignore the first <code>$count-1</code> successful matches. For example:</p>
<pre>        my $foo = &quot;fee fi fo fum&quot;;

        $foo =~ m:nth(1)/ (f\w+) /;        # succeeds (matches &quot;fee&quot;)
        $foo =~ m:nth(2)/ (f\w+) /;        # succeeds (matches &quot;fi&quot;)
        $foo =~ m:nth(3)/ (f\w+) /;        # succeeds (matches &quot;fo&quot;)
        $foo =~ m:nth(4)/ (f\w+) /;        # succeeds (matches &quot;fum&quot;)
        $foo =~ m:nth(5)/ (f\w+) /;        # fails
        $foo =~ m:nth($n)/ (f\w+) /;       # depends on the numeric value of $n

        $foo =~ s:nth(3)/ (f\w+) /bar/;    # $foo now contains: &quot;fee fi bar fum&quot;</pre>
<p>Again there is also a series of abbreviations:</p>
<pre>        $foo =~ m:1st/ (f\w+) /;           # succeeds (matches &quot;fee&quot;)
        $foo =~ m:2nd/ (f\w+) /;           # succeeds (matches &quot;fi&quot;)
        $foo =~ m:3rd/ (f\w+) /;           # succeeds (matches &quot;fo&quot;)
        $foo =~ m:4th/ (f\w+) /;           # succeeds (matches &quot;fum&quot;)
        $foo =~ m:5th/ (f\w+) /;           # fails

        $foo =~ s:3rd/ (f\w+) /bar/;       # $foo now contains: &quot;fee fi bar fum&quot;</pre>
<p>By the way, Perl isn't going to be pedantic about these &quot;ordinal&quot; versions
of repetition specifiers. If you're not a native English speaker, and you
find <code>:1th</code>, <code>:2th</code>, <code>:3th</code>, <code>:4th</code>, etc. easier to remember, that's
perfectly okay.</p>
<p>The various types of repetition modifiers can also be combined
by separating them with additional colons:</p>
<pre>        my $foo = &quot;fee fi fo feh far foo fum &quot;;

        $foo =~ m:2nd:2x/ (f\w+) /;        # succeeds (matches &quot;fi&quot;, &quot;feh&quot;)
        $foo =~ m:each:2nd/ (f\w+) /;      # succeeds (matches &quot;fi&quot;, &quot;feh&quot;, &quot;foo&quot;)
        $foo =~ m:x(2):nth(3)/ (f\w+) /;   # succeeds (matches &quot;fo&quot;, &quot;foo&quot;)
        $foo =~ m:each:3rd/ (f\w+) /;      # succeeds (matches &quot;fo&quot;, &quot;foo&quot;)
        $foo =~ m:2x:4th/ (f\w+) /;        # fails (not enough matches to satisfy :2x)
        $foo =~ m:4th:each/ (f\w+) /;      # succeeds (matches &quot;feh&quot;)

        $foo =~ s:each:2nd/ (f\w+) /bar/;  # $foo now &quot;fee bar fo bar far bar fum &quot;;</pre>
<p>Note that the order in which the two modifiers are specified doesn't matter.</p>
<li><a name=':p5 or :perl5'></a><code>:p5</code> or <code>:perl5</code></li>
<p>This modifier causes Perl 6 to interpret the contents of a rule as
a regular expression in Perl 5 syntax. This is mainly provided as a
transitional aid for porting Perl 5 code. And to mollify the
curmudgeonly.</p>
<p>[Update: Now <code>:P5</code> or <code>:Perl5</code> to avoid confusion with <code>:p</code>.]</p>
<li><a name=':w or :word'></a><code>:w</code> or <code>:word</code></li>
<p>This modifier causes whitespace appearing in the pattern to match optional
whitespace in the string being matched. For example, instead of having
to cope with optional whitespace explicitly:</p>
<pre>        $cmd =~ m/ \s* &lt;keyword&gt; \s* \( [\s* &lt;arg&gt; \s* ,?]* \s* \)/;</pre>
<p>we can just write:</p>
<pre>        $cmd =~ m:w/ &lt;keyword&gt; \( [ &lt;arg&gt; ,?]* \)/;</pre>
<p>The <code>:w</code> modifier is also smart enough to detect those cases where
the whitespace should actually be mandatory. For example:</p>
<pre>        $str =~ m:w/a symmetric ally/</pre>
<p>is the same as:</p>
<pre>        $str =~ m/a \s+ symmetric \s+ ally/</pre>
<p>rather than:</p>
<pre>        $str =~ m/a \s* symmetric \s* ally/</pre>
<p>So it won't accidentally match strings like <code>&quot;asymmetric ally&quot;</code> or
<code>&quot;asymmetrically&quot;</code>.</p>
<p>[Update: This is now the <code>:s</code>/<code>:sigspace</code> modifier, and is implicit
in <code>rule</code> declarations.]</p>
<li><a name=':any'></a><code>:any</code></li>
<p>This modifier causes the rule to match a given string in every possible
way, simultaneously, and then return all the possible matches. For example:</p>
<pre>        my $str = &quot;ahhh&quot;;

        @matches =  $str =~ m/ah*/;         # returns &quot;ahhh&quot;
        @matches =  $str =~ m:any/ah*/;     # returns &quot;ahhh&quot;, &quot;ahh&quot;, &quot;ah&quot;, &quot;a&quot;</pre>
<p>[Update: This split into two modifiers, <code>:overlap</code> and <code>:exhaustive</code>.]</p>
<li><a name=':u0, :u1, :u2, :u3'></a><code>:u0</code>, <code>:u1</code>, <code>:u2</code>, <code>:u3</code></li>
<p>These modifiers specify how the rule matches the dot (<code>.</code>)
metacharacter against Unicode data. If <code>:u0</code> is specified, dot matches
a single byte; if <code>:u1</code> is specified, dot matches a single codepoint
(i.e. one or more bytes representing a single unicode &quot;character&quot;).
If <code>:u2</code> is specified, dot matches a single grapheme (i.e. a base
codepoint followed by zero or more modifier codepoints, such as
accents). If <code>:u3</code> is specified, dot matches an appropriate &quot;something&quot;
in a language-dependent manner.</p>
<p>It's okay to ignore this modifier if you're not using Unicode (and maybe even
if you are). As usual, Perl will try very hard to Do The Right Thing.
To that end, the default behaviour of rules is <code>:u2</code>, unless an
overriding pragma (e.g. <code>use bytes</code>) is in effect.</p>
<p>[Update: Now <code>:bytes</code>, <code>:codes</code>, <code>:graphs</code>, and <code>:langs</code>.]</p>
</ul>
<p>Note that the <code>/s</code>, <code>/m</code>, and <code>/e</code> modifiers are no longer available.
This is because they're no longer needed. The <code>/s</code> isn't needed because
the <code>.</code> (dot) metacharacter now matches newlines as well. When we want
to match &quot;anything except a newline&quot;, we now use the new <code>\N</code> metatoken
(i.e. &quot;opposite of <code>\n</code>&quot;).</p>
<p>The <code>/m</code> modifier isn't required because <code>^</code> and <code>$</code> always mean start and
end of string respectively. To match the start and end of a line, we use
the new <code>^^</code> and <code>$$</code> metatokens instead.</p>
<p>The <code>/e</code> modifier is no longer needed because Perl 6 provides the
<code>$(...)</code> string interpolator (as described in Apocalypse 2). So a
substitution such as:</p>
<pre>        # Perl 5
        s/(\w+)/ get_val_for($1) /e;</pre>
<p>becomes just:</p>
<pre>        # Perl 6
        s/(\w+)/$( get_val_for($1) )/;</pre>
<p>[Update: This is now written:</p>
<pre>        s/(\w+)/{ get_val_for($0) }/;</pre>
<p>or</p>
<pre>        s/ \w+ /{ get_val_for($()) }/;</pre>
<p>]</p>
<a name='Take no prisoners'></a><h1>Take no prisoners</h1>
<p>The first character of the <code>$hunk</code> rule is an opening square bracket.
In Perl 5 that denoted the start of a character class, but not in Perl 6.
In Perl 6, square brackets mark the boundaries of a non-capturing
group. That is, a pair of square brackets in Perl 6 are the same as a
<code>(?:...)</code> in Perl 5, but less line-noisy.</p>
<p>By the way, to get a character class in Perl 6, we need to put the
square brackets inside a pair of metasyntactic angle brackets.
So the Perl 5:</p>
<pre>        # Perl 5
        / [A-Za-z] [0-9]+ /x          # An A-Z or a-z, followed by digits</pre>
<p>would become in Perl 6:</p>
<pre>        # Perl 6
        / &lt;[A-Za-z]&gt; &lt;[0-9]&gt;+ /       # An A-Z or a-z, followed by digits</pre>
<p>[Update: the range hyphens are now replaced by <code>..</code> to be consistent with
ranges elsewhere in Perl 6.]</p>
<p>The Perl 5 complemented character class:</p>
<pre>        # Perl 5
        / [^A-Za-z]+ /x               # One-or-more chars-that-aren't-A-Z-or-a-z</pre>
<p>becomes in Perl 6:</p>
<pre>        # Perl 6
        / &lt;-[A-Za-z]&gt;+ /              #  One-or-more chars-that-aren't-A-Z-or-a-z</pre>
<p>The external minus sign is used (instead of an internal caret) because
Perl 6 allows proper set operations on character classes, and the minus sign is
the &quot;difference&quot; operator. So we could also create:</p>
<pre>        # Perl 6
        / &lt; &lt;alpha&gt; - [A-Za-z] &gt;+ /   # All alphabetics except A-Z or a-z
                                      # (i.e. the accented alphabetics)</pre>
<p>[Update: Would now need to be <code>&lt;+&lt;alpha&gt; - [A..Za..z]&gt;</code> to avoid ambiguity
with &quot;Texas quotes&quot;, and because we want to reserve whitespace as the first
character inside the angles for other uses.]</p>
<p>Explicit character classes were deliberately made a little less
convenient in Perl 6, because they're generally a bad idea in a
Unicode world. For example, the <code>[A-Za-z]</code> character class in the
above examples won't even match standard alphabetic Latin-1
characters like <code>'&Atilde;'</code>, <code>'&eacute;'</code>, <code>'&oslash;'</code>,
let alone alphabetic characters from code-sets such as Cyrillic,
Hiragana, Ogham, Cherokee, or Klingon.</p>
<a name='Meanwhile, back at the $hunk...'></a><h1>Meanwhile, back at the <code>$hunk</code>...</h1>
<p>The non-capturing group of the <code>$hunk</code> pattern groups together three
alternatives, separated by <code>|</code> metacharacters (as in Perl 5).
The first alternative:</p>
<pre>        &lt;$linenum&gt; a :: &lt;$linerange&gt;
        \n                         
        &lt;$appendline&gt;+</pre>
<p>grabs whatever is in the <code>$linenum</code> variable, treats it as a
subpattern, and attempts to match against it. It then matches a
literal letter <code>'a'</code> (or an <code>'A'</code>, because of the <code>:i</code> modifier on the rule).
Then whatever the contents of the <code>$linerange</code> variable match. Then a
newline. Then it tries to match whatever the pattern in <code>$appendline</code>
would match, one-or-more times.</p>
<p>But what about that double-colon after the <code>a</code>? Shouldn't the
pattern have tried to match two colons at that point?</p>
<a name='This or nothing'></a><h1>This or nothing</h1>
<p>Actually, no. The double-colon is a new Perl 6 pattern control
structure. It has no effect (and is ignored) when the pattern is
successfully matching, but if the pattern match should fail, and consequently
back-track over the double-colon -- for example, to try and re-match an
earlier repetition one fewer times -- the double-colon causes the entire
surrounding group (i.e. the surrounding <code>[...]</code> in this case) to fail as well.</p>
<p>That's a useful optimization in this case because, if we match a line
number followed by an <code>'a'</code> but subsequently fail, then there's no
point even trying either of the other two alternatives in the same
group. Because we found an <code>'a'</code>, there's no chance we could match a
<code>'d'</code> or a <code>'c'</code> instead.</p>
<p>So, in general, a double-colon means: &quot;At this point I'm committed to this
alternative within the current group -- don't bother with the others
if this one fails after this point&quot;.</p>
<p>There are other control directives like this too. A single colon means: &quot;Don't
bother backtracking into the previous element&quot;. That's useful in a pattern
like:</p>
<pre>        rx:w/ $keyword [-full|-quick|-keep]+ : end /</pre>
<p>Suppose we successfully match the keyword (as a literal, by the way) and
one-or-more of the three options, but then fail to match <code>'end'</code>.
In that case, there's no point backtracking and trying to match one
fewer options, and <i>still</i> failing to find an <code>'end'</code>. And then
backtracking <i>another</i> option, and failing again, etc. By using
the colon after the repetiton, we tell the matcher to give up after
the very first attempt.</p>
<p>However, the single colon isn't just a &quot;Greed is Good&quot; operator. It's
much more like a &quot;Resistance is Futile&quot; operator. That is, if the
preceding repetition had been non-greedy instead:</p>
<pre>        rx:w/ $keyword [-full|-quick|-keep]+? : end /</pre>
<p>then backtracking over the colon would prevent the <code>+?</code> from attempting
to match <i>more</i> options. Note that this means that <code>x+?:</code> is just a
baroque way of matching exactly one repetition of <code>x</code>, since the
non-greedy repetition initially tries to match the minimal number of
times (i.e. once) and the trailing colon then prevents it from
backtracking and trying longer matches. Likewise, <code>x*?:</code> and <code>x??:</code>
are arcane ways of matching exactly zero repetitions of <code>x</code>.</p>
<p>Generally, though, a single colon tells the pattern matcher that there's
no point trying any other match on the preceding repetition, because
retrying (whether more or fewer repetitions) would just waste time and
would still fail.</p>
<p>There's also a three-colon directive. Three colons means: &quot;If we have
to backtrack past here, cause the entire rule to fail&quot; (i.e. not just
this group). If the double-colon in <code>$hunk</code> had been triple:</p>
<pre>        &lt;$linenum&gt; a ::: &lt;$linerange&gt;
        \n                         
        &lt;$appendline&gt;+</pre>
<p>then matching a line number and an <code>'a'</code> and subsequently failing would
cause the entire <code>$hunk</code> rule to fail immediately (though the <code>$file</code>
rule that invoked it might still match successfully in some other way).</p>
<p>So, in general, a triple-colon specifies: &quot;At this point I'm committed to this
way of matching the current rule -- give up on the rule completely if the
matching process fails at this point&quot;.</p>
<p>Four colons...would just be silly. So, instead, there's a special named
directive: <code>&lt;commit&gt;</code>. Backtracking through a <code>&lt;commit&gt;</code>
causes the entire match to immediately fail. And if the current rule is
being matched as part of a larger rule, that larger rule will fail as
well. In other words, it's the &quot;Blow up this Entire Planet and Possibly
One or Two Others We Noticed on our Way Out Here&quot; operator.</p>
<p>If the double-colon in <code>$hunk</code> had been a <code>&lt;commit&gt;</code> instead:</p>
<pre>        &lt;$linenum&gt; a &lt;commit&gt; &lt;$linerange&gt;
        \n                         
        &lt;$appendline&gt;+</pre>
<p>then matching a line number and an <code>'a'</code> and subsequently
failing would cause the entire <code>$hunk</code> rule to fail immediately, <i>and</i>
would also cause the <code>$file</code> rule that invoked it to fail immediately.</p>
<p>So, in general, a <code>&lt;commit&gt;</code> means: &quot;At this point I'm
committed to this way of completing the current match -- give up
all attempts at matching anything if the matching process fails at
this point&quot;.</p>
<a name='Failing with style'></a><h1>Failing with style</h1>
<p>The other two alternatives:</p>
<pre>        | &lt;$linerange&gt; d :: &lt;$linenum&gt; \n
          &lt;$deleteline&gt;+                 
        | &lt;$linerange&gt; c :: &lt;$linerange&gt; \n
          &lt;$deleteline&gt;+  --- \n  &lt;$appendline&gt;+                </pre>
<p>are just variants on the first.</p>
<p>If none of the three alternatives in the square brackets matches, then the
alternative outside the brackets is tried:</p>
<pre>        |  (\N*) ::: { fail &quot;Invalid diff hunk: $1&quot; }</pre>
<p>This captures a sequence of non-newline characters (<code>\N</code> means &quot;not
<code>\n</code>&quot;, in the same way <code>\S</code> means &quot;not <code>\s</code>&quot; or <code>\W</code> means &quot;not
<code>\w</code>&quot;). Then it invokes a block of Perl code inside the pattern. The
call to <code>fail</code> causes the match to fail at that point, and sets an
associated error message that would subsequently appear in the <code>$!</code>
error variable (and which would also be accessible as part of <code>$0</code>).</p>
<p>[Update: The old <code>$0</code> variable has been renamed <code>$/</code>.]</p>
<p>Note the use of the triple colon after the repetition. It's needed
because the <code>fail</code> in the block will cause the pattern match to
backtrack, but there's no point backing up one character and trying
again, since the original failure was precisely what we wanted. The
presence of the triple-colon causes the entire rule to
fail as soon as the backtracking reaches that point the first time.</p>
<p>The overall effect of the <code>$hunk</code> rule is therefore either to match one
hunk of the diff, or else fail with a relevant error message.</p>
<a name='Home, home on the (line)range'></a><h1>Home, home on the (line)range</h1>
<p>The third and fourth rules:</p>
<pre>    $linerange = rx/ &lt;$linenum&gt; , &lt;$linenum&gt;
                   | &lt;$linenum&gt; 
                   /;

    $linenum = rx/ \d+ /;</pre>
<p>specify that a line number consists of a series of digits, and that a line
range consists of either two line numbers with a comma between them or a single
line number.  The <code>$linerange</code> rule could also have been written:</p>
<pre>    $linerange = rx/ &lt;$linenum&gt; [ , &lt;$linenum&gt; ]? /;</pre>
<p>which might be marginally more efficient, since it doesn't have to
backtrack and rematch the first <code>$linenum</code> in the second alternative.
It's likely, however, that the rule optimizer will detect such cases and
automatically hoist the common prefix out anyway, so it's probably not
worth the decrease in readability to do that manually.</p>
<a name='What's my line?'></a><h1>What's my line?</h1>
<p>The final two rules specify the structure of individual context lines in the
diff (i.e. the lines that say what text is being added or removed by the hunk):</p>
<pre>        $deleteline = rx/^^ \&lt; &lt;sp&gt; (\N* \n) /
        $appendline = rx/^^ \&gt; &lt;sp&gt; (\N* \n) /</pre>
<p>The <code>^^</code> markers ensure that each rule starts at the beginning
of an entire line.</p>
<p>The first character on that line must be either a <code>'&lt;'</code> or a
<code>'&gt;'</code>. Note that we have to escape these characters since angle
brackets are metacharacters in Perl 6. An alternative would be to use
the &quot;literal string&quot; metasyntax:</p>
<pre>        $deleteline = rx/^^ &lt;'&lt;'&gt; &lt;sp&gt; (\N* \n) /
        $appendline = rx/^^ &lt;'&gt;'&gt; &lt;sp&gt; (\N* \n) /</pre>
<p>That is, angle brackets with a single-quoted string inside them match
the string's sequence of characters as literals (including whitespace
and other metatokens).</p>
<p>Or we could have used the quotemeta metasyntax (<code>\Q[...]</code>):</p>
<pre>        $deleteline = rx/^^ \Q[&lt;] &lt;sp&gt; (\N* \n) /
        $appendline = rx/^^ \Q[&gt;] &lt;sp&gt; (\N* \n) /</pre>
<p>Note that Perl 5's <code>\Q...\E</code> construct is replaced in Perl 6 by
just the <code>\Q</code> marker, which now takes a group after it.</p>
<p>[Update: There is no longer any \Q (or \L or \U for that matter).]</p>
<p>We could also have used a single-letter character class:</p>
<pre>        $deleteline = rx/^^ &lt;[&lt;]&gt; &lt;sp&gt; (\N* \n) /
        $appendline = rx/^^ &lt;[&gt;]&gt; &lt;sp&gt; (\N* \n) /</pre>
<p>or even a named character (<code>\c[CHAR NAME HERE]</code>):</p>
<pre>        $deleteline = rx/^^ \c[LEFT ANGLE BRACKET] &lt;sp&gt; (\N* \n) /
        $appendline = rx/^^ \c[RIGHT ANGLE BRACKET] &lt;sp&gt; (\N* \n) /</pre>
<p>Whether any of those MTOWTDI is better than just escaping the angle bracket is,
of course, a matter of personal taste.</p>
<a name='The final frontier'></a><h1>The final frontier</h1>
<p>After the leading angle, a single literal space is expected. Again, we
could have specified that by escapology (<code>\ </code>) or literalness
(<code>&lt;' '&gt;</code>) or quotemetaphysics (<code>\Q[ ]</code>) or character classification
(<code>&lt;[ ]&gt;</code>), or deterministic nomimalism (<code>\c[SPACE]</code>), but Perl 6
also gives us a simple <i>name</i> for the space character: <code>&lt;sp&gt;</code>.
This is the preferred option, since it reduces line-noise and makes the
significant space much harder to miss.</p>
<p>Perl 6 provides predefined names for other useful subpatterns as
well, including:</p>
<ul>
<li><a name='&lt;dot&gt;'></a><code>&lt;dot&gt;</code></li>
<p>which matches a literal dot (<code>'.'</code>) character (i.e. it's a more elegant
synonym for <code>\.</code>);</p>
<li><a name='&lt;lt&gt; and &lt;gt&gt;'></a><code>&lt;lt&gt;</code> and <code>&lt;gt&gt;</code></li>
<p>which match a literal <code>'&lt;'</code> and <code>'&gt;'</code> respectively. These
give us yet another way of writing:</p>
<pre>        $deleteline = rx/^^ &lt;lt&gt; &lt;sp&gt; (\N* \n) /
        $appendline = rx/^^ &lt;gt&gt; &lt;sp&gt; (\N* \n) /</pre>
<li><a name='&lt;ws&gt;'></a><code>&lt;ws&gt;</code></li>
<p>which matches any sequence of whitespace (i.e. it's a more elegant
synonym for <code>\s+</code>). Optional whitespace is, therefore, specified
as <code>&lt;ws&gt;?</code> or <code>&lt;ws&gt;*</code> (Perl 6 will accept either);</p>
<p>[Update: <code>&lt;ws&gt;</code> is now the optional sigspace rule for the current
grammar.]</p>
<li><a name='&lt;alpha&gt;'></a><code>&lt;alpha&gt;</code></li>
<p>which matches a single alphabetic character (i.e. it's like the
character class <code>&lt;[A-Za-z]&gt;</code> but it handles accented characters
and alphabetic characters from non-Roman scripts as well);</p>
<li><a name='&lt;ident&gt;'></a><code>&lt;ident&gt;</code></li>
<p>which is a short-hand for <code>[ [&lt;alpha&gt;|_] \w* ]</code> (i.e. a
standard identifier in many languages, including Perl)</p>
</ul>
<p>Using named subpatterns like these makes rules clearer in intent,
easier to read, and more self-documenting. And, as we'll see
<i><a href='#What's in a name?'>shortly</a></i>, they're fully generalizable...we
can create our own.</p>
<a name='Match-maker, match-maker...'></a><h1>Match-maker, match-maker...</h1>
<p>Finally, we're ready to actually read in and match a diff file. In Perl 5, we'd
do that like so:</p>
<pre>        # Perl 5

        local $/;          # Disable input record separator (enable slurp mode)
        my $text = &lt;&gt;;     # Slurp up input stream into $text

        print &quot;Valid diff&quot; 
            if $text =~ /$file/;</pre>
<p>We could do the same thing in Perl 6 (though the syntax would differ
slightly) and in this case that would be fine. But, in general, it's
clunky to have to slurp up the entire input before we start matching.
The input might be huge, and we might fail early. Or we
might want to match input interactively (and issue an error message as
soon as the input fails to match). Or we might be matching a series of
different formats. Or we might want to be able to leave the input stream
in its original state if the match fails.</p>
<p>The inability to do pattern matches immediately on an input stream is one of
Perl 5's few weaknesses when it comes to text processing. Sure, we can read
line-by-line and apply pattern matching to each line, but trying to
match a construct that may be laid out across an unknown number of lines
is just painful.</p>
<p>Not in Perl 6 though. In Perl 6, we can bind an input stream to a scalar
variable (i.e. like a Perl 5 tied variable) and then just match on the
characters in that stream as if they were already in memory:</p>
<pre>        my $text is from($*ARGS);       # Bind scalar to input stream

        print &quot;Valid diff&quot; 
            if $text =~ /&lt;$file&gt;/;      # Match against input stream</pre>
<p>The important point is that, after the match, only those characters that
the pattern actually matched will have been removed from the input stream.</p>
<p>It may also be possible to skip the variable entirely and just write:</p>
<pre>        print &quot;Valid diff&quot; 
            if $*ARGS =~ /&lt;$file&gt;/;     # Match against input stream</pre>
<p>or:</p>
<pre>        print &quot;Valid diff&quot; 
            if &lt;&gt; =~ /&lt;$file&gt;/;         # Match against input stream</pre>
<p>but that's yet to be decided.</p>
<a name='A cleaner approach'></a><h1>A cleaner approach</h1>
<p>The previous example solves the problem of recognizing a valid diff file quite
nicely (and with only six rules!), but it does so by cluttering
up the program with a series of variables storing those precompiled patterns.</p>
<p>It's as if we were to write a collection of subroutines like this:</p>
<pre>    my $print_name = sub ($data) { print $data{name}, &quot;\n&quot;; };
    my $print_age  = sub ($data) { print $data{age}, &quot;\n&quot;; };
    my $print_addr = sub ($data) { print $data{addr}, &quot;\n&quot;; };

    my $print_info = sub ($data) {
        $print_name($data);
        $print_age($data);
        $print_addr($data);
    };

    # and later...

    $print_info($info);</pre>
<p>You <i>could</i> do it that way, but it's not the right way to do it.
The right way to do it is as a collection of named subroutines or methods,
often collected together in the namespace of a class or module:</p>
<pre>    module Info {

        sub print_name ($data) { print $data{name}, &quot;\n&quot;; }
        sub print_age ($data)  { print $data{age}, &quot;\n&quot;; }
        sub print_addr ($data) { print $data{addr}, &quot;\n&quot;; }

        sub print_info ($data) {
            print_name($data);
            print_age($data);
            print_addr($data);
        }
    }

    Info::print_info($info);</pre>
<p>So it is with Perl 6 patterns. You <i>can</i> write them as a series of
pattern objects created at run-time, but they're much better specified as
a collection of named patterns, collected together at compile-time
in the namespace of a grammar.</p>
<p>Here's the previous diff-parsing example rewritten that way
(and with a few extra bells-and-whistles added in):</p>
<pre>    grammar Diff {
        rule file { ^  &lt;hunk&gt;*  $ }

        rule hunk :i { 
            [ &lt;linenum&gt; a :: &lt;linerange&gt; \n
              &lt;appendline&gt;+ 
            |
              &lt;linerange&gt; d :: &lt;linenum&gt; \n
              &lt;deleteline&gt;+
            |
              &lt;linerange&gt; c :: &lt;linerange&gt; \n
              &lt;deleteline&gt;+
              --- \n
              &lt;appendline&gt;+
            ]
          |
            &lt;badline(&quot;Invalid diff hunk&quot;)&gt;
        }

        rule badline ($errmsg) { (\N*) ::: { fail &quot;$errmsg: $1&quot; }

        rule linerange { &lt;linenum&gt; , &lt;linenum&gt;
                       | &lt;linenum&gt;
                       }

        rule linenum { \d+ }

        rule deleteline { ^^ &lt;out_marker&gt; (\N* \n) }
        rule appendline { ^^ &lt;in_marker&gt;  (\N* \n) }

        rule out_marker { \&lt;  &lt;sp&gt; }
        rule in_marker  { \&gt;  &lt;sp&gt; }
    }

    # and later...

    my $text is from($*ARGS);

    print &quot;Valid diff&quot; 
        if $text =~ /&lt;Diff.file&gt;/;</pre>
<a name='What's in a name?'></a><h1>What's in a name?</h1>
<p>The <code>grammar</code> declaration creates a new namespace for rules
(in the same way a <code>class</code> or <code>module</code> declaration creates
a new namespace for methods or subroutines). If a block is
specified after the grammar's name:</p>
<pre>        grammar HTML {

            rule file :iw { \Q[&lt;HTML&gt;]  &lt;head&gt;  &lt;body&gt;  \Q[&lt;/HTML&gt;] }

            rule head :iw { \Q[&lt;HEAD&gt;]  &lt;head_tag&gt;+  \Q[&lt;HEAD&gt;] }

            # etc.

        } # Explicit end of HTML grammar</pre>
<p>then that new namespace is confined to that block. Otherwise the
namespace continues until the end of the source section of the
current file:</p>
<pre>        grammar HTML;

        rule file :iw { \Q[&lt;HTML&gt;]  &lt;head&gt;  &lt;body&gt;  \Q[&lt;/HTML&gt;] }

        rule head :iw { \Q[&lt;HEAD&gt;]  &lt;head_tag&gt;+  \Q[&lt;HEAD&gt;] }

        # etc.

        # Implicit end of HTML grammar
        __END__</pre>
<p>Note that, as with the blockless variants on <code>class</code> and <code>module</code>,
this form of the syntax is designed to simplify one-namespace-per-file
situations. It's a compile-time error to put two or more blockless
grammars, classes or modules in a single file.</p>
<p>Within the namespace, named rules are defined using the <code>rule</code>
declarator. It's analogous to the <code>sub</code> declarator within a
module, or the <code>method</code> declarator within a class. Just like
a class method, a named rule has to be invoked through its grammar
if we refer to it outside its own namespace. That's why the actual
match became:</p>
<pre>        $text =~ /&lt;Diff.file&gt;/;         # Invoke through grammar</pre>
<p>If we want to match a named rule, we put the name in angle brackets.
Indeed, many of the constructs we've already seen -- <code>&lt;sp&gt;</code>,
<code>&lt;ws&gt;</code>, <code>&lt;ident&gt;</code>, <code>&lt;alpha&gt;</code>, <code>&lt;commit&gt;</code> --
are really just predefined named rules that come standard with Perl 6.</p>
<p>Like subroutines and methods, within their own namespace, rules don't
have to be qualified. Which is why we can write things like:</p>
<pre>        rule linerange { &lt;linenum&gt; , &lt;linenum&gt;
                       | &lt;linenum&gt;
                       }</pre>
<p>instead of:</p>
<pre>        rule linerange { &lt;Diff.linenum&gt; , &lt;Diff.linenum&gt;
                       | &lt;Diff.linenum&gt;
                       }</pre>
<p>Using named rules has several significant advantages, apart from making
the patterns look cleaner. For one thing, the compiler may be able to
optimize the embedded named rules better. For example, it could inline
the attempts to match <code>&lt;linenum&gt;</code> within the <code>linerange</code> rule. In
the <code>rx</code> version:</p>
<pre>        $linerange = rx{ &lt;$linenum&gt; , &lt;$linenum&gt;
                       | &lt;$linenum&gt;
                       };</pre>
<p>that's not possible, since the pattern matching mechanism won't know
what's in <code>$linenum</code> until it actually tries to perform the match.</p>
<p>By the way, we <i>can</i> still use interpolated <code>&lt;$subrule&gt;</code>-ish
subpatterns in a named rule, and we can use named subpatterns
in an <code>rx</code>-ish rule. The difference between <code>rule</code> and <code>rx</code>
is just that a <code>rule</code> can have a name and must use <code>{...}</code> as its
delimiters, whereas an <code>rx</code> doesn't have a name and can use
any allowed delimiters.</p>
<p>[Update: Wherever this document uses the <code>rule</code> keyword, that is now
the <code>regex</code> keyword.  There are keywords for <code>token</code> and <code>rule</code> but
they do something different now.]</p>
<a name='Bad line! No match!'></a><h1>Bad line! No match!</h1>
<p>This version of the diff parser has an additional rule, named <code>badline</code>.
This rule illustrates another similarity between rules and subroutines/methods:
rules can take arguments. The <code>badline</code> rule factors out the error message
creation at the end of the <code>hunk</code> rule. Previously that rule ended with:</p>
<pre>        |  (\N*) ::: { fail &quot;Invalid diff hunk: $1&quot; }</pre>
<p>but in this version it ends with:</p>
<pre>        |  &lt;badline(&quot;Invalid diff hunk&quot;)&gt;</pre>
<p>That's a much better abstraction of the error condition. It's easier to
understand and easier to maintain, but it does require us to be able to pass
an argument (the error message) to the new <code>badline</code> subrule. To do
that, we simply declare it to have a parameter list:</p>
<pre>        rule badline($errmsg) { (\N*) ::: { fail &quot;$errmsg: $1&quot; }</pre>
<p>Note the strong syntactic parallel with a subroutine definition:</p>
<pre>        sub  subname($param)  { ... }</pre>
<p>The argument is passed to a subrule by placing it in parentheses
after the rule name within the angle brackets:</p>
<pre>        |  &lt;badline(&quot;Invalid diff hunk&quot;)&gt;</pre>
<p>The argument can also be passed without the parentheses, but then
it is interpreted as if it were the body of a separate rule:</p>
<pre>        rule list_of ($pattern) { 
                &lt;$pattern&gt; [ , &lt;$pattern&gt; ]*
        }

        # and later...

        $str =~ m:w/  \[                  # Literal opening square bracket
                      &lt;list_of \w\d+&gt;     # Call list_of subrule passing rule rx/\w\d+/
                      \]                  # Literal closing square bracket
                   /;</pre>
<p>A rule can take as many arguments as it needs to:</p>
<pre>        rule seplist($elem, $sep) {
                &lt;$elem&gt;  [ &lt;$sep&gt; &lt;$elem&gt; ]*
        }</pre>
<p>and those arguments can also be passed by name, using the standard
Perl 6 pair-based mechanism (as described in Apocalypse 3).</p>
<pre>        $str =~ m:w/
                    \[                                      # literal left square bracket
                    &lt;seplist(sep=&gt;&quot;:&quot;, elem=&gt;rx/&lt;ident&gt;/)&gt;  # colon-separated list of identifiers
                    \]                                      # literal right square bracket
                   /;</pre>
<p>Note that the list's element specifier is itself an anonymous rule,
which the <code>seplist</code> rule will subsequently interpolate as a pattern (because
the <code>$elem</code> parameter appears in angle brackets within <code>seplist</code>).</p>
<a name='Thinking ahead'></a><h1>Thinking ahead</h1>
<p>The only other change in the grammar version of the diff parser is that
the matching of the <code>'&lt;'</code> and <code>'&gt;'</code> at the start of the context
lines has been factored out. Whereas before we had:</p>
<pre>        $deleteline = rx/^^ \&lt; &lt;sp&gt; (\N* \n) /
        $appendline = rx/^^ \&gt; &lt;sp&gt; (\N* \n) /</pre>
<p>now we have:</p>
<pre>        rule deleteline { ^^ &lt;out_marker&gt; (\N* \n) }
        rule appendline { ^^ &lt;in_marker&gt;  (\N* \n) }

        rule out_marker { \&lt;  &lt;sp&gt; }
        rule in_marker  { \&gt;  &lt;sp&gt; }</pre>
<p>That seems like a step backwards, since it complicated the grammar for
no obvious benefit, but the benefit will be reaped <i><a href='#Different diffs'>later</a></i>
when we discover another type of diff file that uses different
markers for incoming and outgoing lines.</p>
<a name='What you match is what you get'></a><h1>What you match is what you get</h1>
<p>Both the variable-based and grammatical versions of the code above do a
great job of <i>recognizing</i> a diff, but that's all they do. If we only
want syntax checking, that's fine. But, generally, if we're parsing data
what we really want is to do something useful with it: transform it into
some other syntax, make changes to its contents, or perhaps convert it
to a Perl internal data structure for our program to manipulate.</p>
<p>Suppose we did want to build a hierarchical Perl data structure
representing the diff that the above examples match. What extra
code would we need?</p>
<p>None.</p>
<p>That's right. Whenever Perl 6 matches a pattern, it <i>automatically</i>
builds a &quot;result object&quot; representing the various components of the
match.</p>
<p>That result object is named <code>$0</code> (the program's name is now
<code>$*PROG</code>) and it's lexical to the scope in which the match occurs. The
result object stores (amongst other things) the complete string matched
by the pattern, and it evaluates to that string when used in a string
context. For example:</p>
<pre>        if ($text =~ /&lt;Diff.file&gt;/) {
                $difftext = $0;
        }</pre>
<p>That's handy, but not really useful for extracting data structures.
However, in addition, any components within a match that were captured
using parentheses become elements of the object's array attribute, and are
accessible through its array index operator. So,
for example, when a pattern such as:</p>
<pre>    rule linenum_plus_comma { (\d+) (,?) };</pre>
<p>matches sucessfully, the array element 1 of the result object
(i.e. <code>$0[1]</code>) is assigned the result of the first parenthesized
capture (i.e. the digits), whilst the array element 2
(<code>$0[2]</code>) receives the comma. Note that array element
zero of any result object is assigned the complete string that the pattern
matched.</p>
<p>[Update: This has all changed.  <code>$/[0]</code> is the first result, same as <code>$0</code>.
The entire result is extracted from a result object by casting to scalar,
with <code>$()</code> returning the scalar value of <code>$($/)</code>.]</p>
<p>There are also abbreviations for each of the array elements of <code>$0</code>.
<code>$0[1]</code> can also be referred to as...surprise, surprise...<code>$1</code>,
<code>$0[2]</code> can also be referred to as <code>$2</code>, <code>$0[3]</code> as <code>$3</code>, etc.
Like <code>$0</code>, each of these numeric variables is also lexical to the scope
in which the pattern match occurred.</p>
<p>The parts of a matched string that were matched by a named
subrule become entries in the result object's hash attribute, and are
subsequently accessible through its hash lookup operator.
So, for example, when the pattern:</p>
<pre>        rule deleteline { ^^ &lt;out_marker&gt; (\N* \n) }</pre>
<p>matches, the result object's hash entry for the key <code>'out_marker'</code> (i.e.
<code>$0{out_marker}</code>) will contain the result object returned by the successful
nested match of the <code>out_marker</code> subrule.</p>
<p>[Update: Curly subscripts no longer autoquote, so that's now
<code>$/&lt;outmarker&gt;</code>, or <code>$&lt;outmarker&gt;</code> for short.]</p>
<a name='A hypothetical solution to a very real problem'></a><h1>A hypothetical solution to a very real problem</h1>
<p>Named capturing into a hash is very convenient, but it doesn't work so well
for a rule like:</p>
<pre>        rule linerange {
              &lt;linenum&gt; , &lt;linenum&gt;
            | &lt;linenum&gt;
        }</pre>
<p>The problem is that the hash attribute of the rule's
<code>$0</code> can only store one entry with the key <code>'linenum'</code>.
So if the <code>&lt;linenum&gt; , &lt;linenum&gt;</code> alternative matches,
then the result object from the second match of
<code>&lt;linenum&gt;</code> will overwrite the entry for the first
<code>&lt;linenum&gt;</code> match.</p>
<p>The solution to this is a new Perl 6 pattern matching feature known
as &quot;hypothetical variables&quot;. A hypothetical variable is
a variable that is declared and bound within a pattern match
(i.e. inside a closure within a rule).
The variable is declared, not with a <code>my</code>, <code>our</code>, or <code>temp</code>,
but with the new keyword <code>let</code>, which was chosen because it's what
mathematicians and other philosophers use to indicate a hypothetical
assumption.</p>
<p>Once declared, a hypothetical variable is then bound using the
normal binding operator. For example:</p>
<pre>        rule checked_integer {
                (\d+)                   # Match and capture one-or-more digits
                { let $digits := $1 }   # Bind to hypothetical var $digits
                -                       # Match a hyphen
                (\d)                    # Match and capture one digit
                { let $check := $2 }    # Bind to hypothetical var $check
        }</pre>
<p>In this example, if a sequence of digits is found, then the <code>$digits</code>
variable is bound to that substring. Then, if the dash and check-digit
are matched, the digit is bound to <code>$check</code>. However, if the dash or
digit is not matched, the match will fail and backtrack through the
closure. This backtracking causes the <code>$digits</code> hypothetical variable
to be automatically <i>un-bound</i>. Thus, if a rule fails to match,
the hypothetical variables within it are not associated with any value.</p>
<p>Each hypothetical variable is really just another name for the
corresponding entry in the result object's hash attribute. So binding
a hypothetical variable like <code>$digits</code> within a rule actually sets the
<code>$0{digits}</code> element of the rule's result object.</p>
<p>So, for example, to distinguish the two line numbers within a
line range:</p>
<pre>        rule linerange {
              &lt;linenum&gt; , &lt;linenum&gt;
            | &lt;linenum&gt;
        }</pre>
<p>we could bind them to two separate hypothetical variables -- say,
<code>$from</code> and <code>$to</code> -- like so:</p>
<pre>        rule linerange {
              (&lt;linenum&gt;)               # Match linenum and capture result as $1
              { let $from := $1 }       # Save result as hypothetical variable
              ,                         # Match comma
              (&lt;linenum&gt;)               # Match linenum and capture result as $2
              { let $to := $2 }         # Save result as hypothetical variable
            |
              (&lt;linenum&gt;)               # Match linenum and capture result as $3
              { let $from := $3 }       # Save result as hypothetical variable
        }</pre>
<p>Now our result object has a hash entry <code>$0{from}</code> and (maybe) one for
<code>$0{to}</code> (if the first alternative was the one that matched). In fact,
we could <i>ensure</i> that the result always has a <code>$0{to}</code>, by
setting the corresponding hypothetical variable in the second
alternative as well:</p>
<pre>        rule linerange {
              (&lt;linenum&gt;)
              { let $from := $1 }
              ,         
              (&lt;linenum&gt;)
              { let $to := $2 }
            |
              (&lt;linenum&gt;)
              { let $from := $3; let $to := $from }
        }</pre>
<p>Problem solved.</p>
<p>But only by introducing a new problem. All that hypothesizing made our
rule ugly and complex. So Perl 6 provides a much prettier short-hand:</p>
<pre>        rule linerange {
              $from := &lt;linenum&gt;          # Match linenum rule, bind result to $from
              ,                           # Match comma
              $to := &lt;linenum&gt;            # Match linenum rule, bind result to $to
            |                             # Or...
              $from := $to := &lt;linenum&gt;   # Match linenum rule,
        }                                 #   bind result to both $from and $to</pre>
<p>or, more compactly:</p>
<pre>        rule linerange {
              $from:=&lt;linenum&gt; , $to:=&lt;linenum&gt;
            | $from:=$to:=&lt;linenum&gt;
        }</pre>
<p>If a Perl 6 rule contains a variable that is immediately followed by
the binding operator (<code>:=</code>), that variable is never interpolated.
Instead, it is treated as a hypothetical variable, and bound to the
result of the next component of the rule (in the above examples,
to the result of the <code>&lt;linenum&gt;</code> subrule match).</p>
<p>[Update: Any variable can be &quot;hypotheticalized&quot; via <code>let</code>, so we
no longer call these hypotheticals.  You bind to <code>$&lt;from&gt;</code> to
capture a named field now, and may bind to <code>$from</code> only if that is
an externally predeclared variable.]</p>
<p>You can also use hypothetical arrays and hashes, binding them to
a component that captures repeatedly. For example, we might choose
to name our set of hunks:</p>
<pre>        rule file { ^  @adonises := &lt;hunk&gt;*  $ }</pre>
<p>collecting all the <code>&lt;hunk&gt;</code> matches into a single array
(which would then be available after the match as <code>$0{'@adonises'}</code>. Note that
the sigil is included in the key in this case).</p>
<p>[Update: Now you bind to @&lt;adonises&gt;, and the sigil is not included.]</p>
<p>Or we might choose to bind a hypothetical hash:</p>
<pre>        rule config {
            %init :=            # Hypothetically, bind %init to...
                [               # Start of group
                    (&lt;ident&gt;)   # Match and capture an identifier
                    \h*=\h*     # Match an equals sign with optional horizontal whitespace
                    (\N*)       # Match and capture the rest of the line
                    \n          # Match the newline
                ]*
        }</pre>
<p>where each repetition of the <code>[...]*</code> grouping captures
two substrings on each repetition and converts them to a key/value pair,
which is then added to the hash. The first captured substring in each
repetition becomes the key, and the second captured substring becomes
its associated value. The hypothetical <code>%init</code> hash is also available
through the rule's result object, as <code>$0{'%init'}</code> (again, with the
sigil as part of the key).</p>
<p>[Update: The current rules for all these bindings are detailed in S05.</p>
<a name='The nesting instinct'></a><h1>The nesting instinct</h1>
<p>Of course, those line number submatches in:</p>
<pre>        rule linerange {
              $from:=&lt;linenum&gt; , $to:=&lt;linenum&gt;
            | $from:=$to:=&lt;linenum&gt;
        }</pre>
<p>will have returned their own result objects. And it's a reference to those
nested result objects that actually gets stored in <code>linerange</code>'s
<code>$0{from}</code> and <code>$0{to}</code>.</p>
<p>Likewise, in the next higher rule:</p>
<pre>    rule hunk :i { 
        [ &lt;linenum&gt; a :: &lt;linerange&gt; \n
          &lt;appendline&gt;+ 
        |
          &lt;linerange&gt; d :: &lt;linenum&gt; \n
          &lt;deleteline&gt;+
        |
          &lt;linerange&gt; c :: &lt;linerange&gt; \n
          &lt;deleteline&gt;+
          --- \n
          &lt;appendline&gt;+
        ]
    };</pre>
<p>the match on <code>&lt;linerange&gt;</code> will return <i>its</i> <code>$0</code> object.
So, within the <code>hunk</code> rule, we could access the &quot;from&quot; digits
of the line range of the hunk as: <code>$0{linerange}{from}</code>.</p>
<p>Likewise, at the highest level:</p>
<pre>    rule file { ^  &lt;hunk&gt;*  $ }</pre>
<p>we are matching a series of hunks, so the hypothetical <code>$hunk</code>
variable (and hence <code>$0{hunk}</code>) will contain a result object whose array
attribute contains the series of result objects returned by each
individual <code>&lt;hunk&gt;</code> match.</p>
<p>So, for example, we could access the &quot;from&quot; digits of the line range of
the third hunk as: <code>$0{hunk}[2]{linerange}{from}</code>.</p>
<p>[Update: <code>$&lt;hunk&gt;[2]&lt;linerange&gt;&lt;from&gt;</code> now.</p>
<a name='Extracting the insertions'></a><h1>Extracting the insertions</h1>
<p>More usefully, we could locate and print every line in the diff that was
being inserted, regardless of whether it was inserted by an &quot;append&quot; or
a &quot;change&quot; hunk. Like so:</p>
<pre>    my $text is from($*ARGS);

    if $text =~ /&lt;Diff.file&gt;/ {
        for @{ $0{file}{hunk} } -&gt; $hunk {
             print @{$hunk{appendline}}
                 if $hunk{appendline};
        }
    }</pre>
<p>[Update: The <code>@{...}</code> construct is now <code>@(...)</code>.  A <code>.list</code> would
probably be more readable though.  And smartmatch is <code>~~</code> now.]</p>
<p>Here, the <code>if</code> statement attempts to match the text against the pattern
for a diff file. If it succeeds, the <code>for</code> loop grabs the <code>&lt;hunk&gt;*</code>
result object, treats it as an array, and then iterates each hunk match
object in turn into <code>$hunk</code>. The array of append lines for each hunk
match is then printed (if there is in fact a reference to that array in
the hunk).</p>
<a name='Don't just match there; do something!'></a><h1>Don't just match there; do something!</h1>
<p>Because Perl 6 patterns can have arbitrary code blocks inside them, it's
easy to have a pattern actually perform syntax transformations whilst
it's parsing. That's often a useful technique because it allows
us to manipulate the various parts of a hierarchical representation
locally (within the rules that recognize them).</p>
<p>For example, suppose we wanted to &quot;reverse&quot; the diff file. That is,
suppose we had a diff that specified the changes required to
transform file A to file B, but we needed the back-transformation
instead: from file B to file A. That's relatively easy to create.
We just turn every &quot;append&quot; into a &quot;delete&quot;, every &quot;delete&quot; into
an &quot;append&quot;, and reverse every &quot;change&quot;.</p>
<p>The following code does exactly that:</p>
<pre>    grammar ReverseDiff {
        rule file { ^  &lt;hunk&gt;*  $ }

        rule hunk :i { 
            [ &lt;linenum&gt; a :: &lt;linerange&gt; \n
              &lt;appendline&gt;+ 
              { @$appendline =~ s/&lt;in_marker&gt;/&lt; /;
                let $0 := &quot;${linerange}d${linenum}\n&quot;
                        _ join &quot;&quot;, @$appendline;
              }
            |
              &lt;linerange&gt; d :: &lt;linenum&gt; \n
              &lt;deleteline&gt;+
              { @$deleteline =~ s/&lt;out_marker&gt;/&gt; /;
                let $0 := &quot;${linenum}a${linerange}\n&quot;
                        _ join &quot;&quot;, @$deleteline;
              }
            |
              $from:=&lt;linerange&gt; c :: $to:=&lt;linerange&gt; \n
              &lt;deleteline&gt;+
              --- \n
              &lt;appendline&gt;+
              { @$appendline =~ s/&lt;in_marker&gt;/&lt;/;</pre>
<p>[Update: Smartmatch is now <code>~~</code>.]</p>
<pre>                @$deleteline =~ s/&lt;out_marker&gt;/&gt;/;
                let $0 := &quot;${to}c${from}\n&quot;</pre>
<p>[Update: That <code>${to}</code> syntax is very, very dead now.  Use {$to} instead.]</p>
<pre>                        _ join(&quot;&quot;, @$appendline)</pre>
<p>[Update: String concatenation is now <code>~</code>.  And just say <code>$appendline.join</code>
to join with null strings.]</p>
<pre>                        _ &quot;---\n&quot;
                        _ join(&quot;&quot;, @$deleteline);
              }
            ]
          |
            &lt;badline(&quot;Invalid diff hunk&quot;)&gt;
        }

        rule badline ($errmsg) { (\N*) ::: { fail &quot;$errmsg: $1&quot; } }

        rule linerange { $from:=&lt;linenum&gt; , $to:=&lt;linenum&gt;
                       | $from:=$to:=&lt;linenum&gt;
                       }

        rule linenum { (\d+) }

        rule deleteline { ^^ &lt;out_marker&gt; (\N* \n) }
        rule appendline { ^^ &lt;in_marker&gt;  (\N* \n) }

        rule out_marker { \&lt;  &lt;sp&gt; }
        rule in_marker  { \&gt;  &lt;sp&gt; }
    }

    # and later...

    my $text is from($*ARGS);

    print @{ $0{file}{hunk} }
        if $text =~ /&lt;Diff.file&gt;/;</pre>
<p>The rule definitions for <code>file</code>, <code>badline</code>, <code>linerange</code>, <code>linenum</code>,
<code>appendline</code>, <code>deleteline</code>, <code>in_marker</code> and <code>out_marker</code> are exactly
the same as before.</p>
<p>All the work of reversing the diff is performed in the <code>hunk</code> rule.
To do that work, we have to extend each of the three main alternatives
of that rule, adding to each a closure that changes the result object
it returns.</p>
<p>[Update: Now you can just set the desired scalar result object with a
<code>make</code> call in the closure.]</p>
<a name='Smarter alternatives'></a><h1>Smarter alternatives</h1>
<p>In the first alternative (which matches &quot;append&quot; hunks), we match as
before:</p>
<pre>        &lt;linenum&gt; a :: &lt;linerange&gt; \n
        &lt;appendline&gt;+ </pre>
<p>But then we execute an embedded closure:</p>
<pre>        { @$appendline =~ s/&lt;in_marker&gt;/&lt;/;
          let $0 := &quot;${linerange}d${linenum}\n&quot;
                  _ join &quot;&quot;, @$appendline;
        }</pre>
<p>The first line reverses the &quot;marker&quot; arrows on each line of data that
was previously being appended, using the smart-match operator to
apply the transformation to each line. Note too, that we reuse the
<code>in_marker</code> rule within the substitution.</p>
<p>Then we bind the result object (i.e. the hypothetical variable <code>$0</code>) to
a string representing the &quot;reversed&quot; append hunk. That is, we reverse the
order of the line range and line number components, put a <code>'d'</code> (for &quot;delete&quot;)
between them, and then follow that with all the reversed data:</p>
<pre>          let $0 := &quot;${linerange}d${linenum}\n&quot;
                  _ join &quot;&quot;, @$appendline;</pre>
<p>The changes to the &quot;delete&quot; alternative are exactly symmetrical.
Capture the components as before, reverse the marker arrows,
reverse the <code>$linerange</code> and <code>$linenum</code>, change the <code>'d'</code> to an <code>'a'</code>,
and append the reversed data lines.</p>
<p>In the third alternative:</p>
<pre>        $from:=&lt;linerange&gt; c :: $to:=&lt;linerange&gt; \n
        &lt;deleteline&gt;+   
        --- \n
        &lt;appendline&gt;+
        { @$appendline =~ s/&lt;in_marker&gt;/&lt;/;
          @$deleteline =~ s/&lt;out_marker&gt;/&gt;/;
          let $0 := &quot;${to}c${from}\n&quot;
                  _ join(&quot;&quot;, @$appendline)
                  _ &quot;---\n&quot;
                  _ join(&quot;&quot;, @$deleteline);
        }</pre>
<p>there are line ranges on both sides of the <code>'c'</code>. So we
need to give them distinct names, by binding them to extra hypothetical
variables: <code>$from</code> and <code>$to</code>. We then reverse the order of two line
ranges, but leave the <code>'c'</code> as it was (because we're simply changing
something back to how it was previously). The markers on both the append
and delete lines are reversed, and then the order of the two sets of
lines is also reversed.</p>
<p>Once those transformations has been performed on each hunk (i.e. as it's
being matched!), the result of successfully matching any <code>&lt;hunk&gt;</code>
subrule will be a string in which the matched hunk has already been
reversed.</p>
<p>All that remains is to match the text against the grammar, and
print out the (modified) hunks:</p>
<pre>    print @{ $0{file}{hunk} }
        if $text =~ /&lt;ReverseDiff.file&gt;/;</pre>
<p>And, since the <code>file</code> rule is now in the ReverseDiff grammar's namespace,
we need to call the rule through that grammar. Note the way the
syntax for doing that continues the parallel with methods and classes.</p>
<a name='Rearranging the deck-chairs...'></a><h1>Rearranging the deck-chairs...</h1>
<p>It might have come as a surprise that we were allowed to bind
the pattern's <code>$0</code> result object directly, but there's nothing magical
about it. <code>$0</code> turns out to be just another hypothetical variable...the
one that happens to be returned when the match is complete.</p>
<p>[Update: For <code>$0</code> read <code>$/</code> here.]</p>
<p>Likewise, <code>$1</code>, <code>$2</code>, <code>$3</code>, etc. are all hypotheticals, and can also be
explicitly bound in a rule. That's very handy for ensuring that the
right substring always turns up in the right numbered variable. For
example, consider a Perl 6 rule to match simple Perl 5 method calls
(matching <i>all</i> Perl 5 method calls would, of course, require a much
more sophisticated rule):</p>
<pre>        rule method_call :w {
            # Match direct syntax:   $var-&gt;meth(...)
            \$  (&lt;ident&gt;)  -\&gt;  (&lt;ident&gt;)  \(  (&lt;arglist&gt;)  \)

          | # Match indirect syntax: meth $var (...)
            (&lt;ident&gt;)  \$  (&lt;ident&gt;)  [ \( (&lt;arglist&gt;) \) | (&lt;arglist&gt;) ]
        }

        my ($varname, methodname, $arglist);

        if ($source_code =~ / $0 := &lt;method_call&gt; /) {
            $varname    = $1 // $5;
            $methodname = $2 // $4;
            $arglist    = $3 // $6 // $7;
        }</pre>
<p>By binding the match's <code>$0</code> to the result of the <code>&lt;method_call&gt;</code>
subrule, we bind its <code>$0[1]</code>, <code>$0[2]</code>, <code>$0[3]</code>, etc. to those array
elements in <code>&lt;method_call&gt;</code>'s result object. And thereby bind
<code>$1</code>, <code>$2</code>, <code>$3</code>, etc. as well. Then it's just a matter of sorting
out which numeric variable ended up with which bit of the method call.</p>
<p>That's okay, but it would be much better if we could guarantee that
the variable name was always in <code>$1</code>, the method name in <code>$2</code>,
and the argument list in <code>$3</code>. Then we could replace the last six lines
above with just:</p>
<pre>        my ($varname, methodname, $arglist) =
                $source_code =~ / $0 := &lt;method_call&gt; /;</pre>
<p>In Perl 5 there was no way to do that, but in Perl 6 it's relatively easy.
We just modify the <code>method_call</code> rule like so:</p>
<pre>        rule method_call :w {
            \$  $1:=&lt;ident&gt;  -\&gt;  $2:=&lt;ident&gt;  \( $3:=&lt;arglist&gt; \)
          | $2:=&lt;ident&gt;  \$  $1:=&lt;ident&gt;  [ \( $3:=&lt;arglist&gt; \) | $3:=&lt;arglist&gt; ]
        }</pre>
<p>Or, annotated:</p>
<pre>        rule method_call :w {
            \$                          #   Match a literal $
            $1:=&lt;ident&gt;                 #   Match the varname, bind it to $1
            -\&gt;                         #   Match a literal -&gt;
            $2:=&lt;ident&gt;                 #   Match the method name, bind it to $2
            \(                          #   Match an opening paren
            $3:=&lt;arglist&gt;               #   Match the arg list, bind it to $3
            \)                          #   Match a closing paren
          |                             # Or
            $2:=&lt;ident&gt;                 #   Match the method name, bind it to $2
            \$                          #   Match a literal $
            $1:=&lt;ident&gt;                 #   Match the varname, bind it to $1
            [                           #   Either...
              \( $3:=&lt;arglist&gt; \)       #     Match arg list in parens, bind it to $3
            |                           #   Or...
                 $3:=&lt;arglist&gt;          #     Just match arg list, bind it to $3
            ]
        }</pre>
<p>Now the rule's <code>$1</code> is bound to the variable name, regardless of which
alternative matches. Likewise <code>$2</code> is bound to the method name in
either branch of the <code>|</code>, and <code>$3</code> is associated with the argument
list, no matter which of the <i>three</i> possible ways it was matched.</p>
<p>Of course, that's still rather ugly (especially if we have to write all those
comments just so others can understand how clever we were).</p>
<p>So an even better solution is just to use proper named rules (with their
handy auto-capturing behaviour) for everything. And then slice the required
information out of the result object's hash attribute:</p>
<pre>        rule varname    { &lt;ident&gt; }
        rule methodname { &lt;ident&gt; }

        rule method_call :w {
            \$  &lt;varname&gt;  -\&gt;  &lt;methodname&gt;  \( &lt;arglist&gt; \)
          | &lt;methodname&gt;  \$  &lt;varname&gt;  [ \( &lt;arglist&gt; \) | &lt;arglist&gt; ]
        }

        $source_code =~ / &lt;method_call&gt; /;

        my ($varname, $methodname, $arglist) =
                $0{method_call}{&quot;varname&quot;,&quot;methodname&quot;,&quot;arglist&quot;}</pre>
<p>[Update: Make that <code>$&lt;method_call&gt;&lt;varname methodname arglist&gt;</code> now.]</p>
<a name='Deriving a benefit'></a><h1>Deriving a benefit</h1>
<p>As the above examples illustrate, using named rules in grammars provides
a cleaner syntax and a reduction in the number of variables required in a
parsing program. But, beyond those advantages, and the obvious benefits
of moving rule construction from run-time to compile-time, there's yet
another significant way to gain from placing named rules inside a grammar: we
can <i>inherit</i> from them.</p>
<p>For example, the ReverseDiff grammar is almost the same as the
normal Diff grammar. The only difference is in the <code>hunk</code> rule.
So there's no reason why we shouldn't just have ReverseDiff inherit
all that sameness, and simply redefine its notion of <code>hunk</code>-iness.
That would look like this:</p>
<pre>    grammar ReverseDiff is Diff {

        rule hunk :i { 
            [ &lt;linenum&gt; a :: &lt;linerange&gt; \n
              &lt;appendline&gt;+ 
              { $appendline =~ s/ &lt;in_marker&gt; /&lt;/;
                let $0 := &quot;${linerange}d${linenum}\n&quot;
                        _ join &quot;&quot;, @$appendline;
              }
            |
              &lt;linerange&gt; d :: &lt;linenum&gt; \n
              &lt;deleteline&gt;+
              { $deleteline =~ s/ &lt;out_marker&gt; /&gt;/;
                let $0 := &quot;${linenum}a${linerange}\n&quot;
                        _ join &quot;&quot;, @$deleteline;
              }
            |
              $from:=&lt;linerange&gt; c :: $to:=&lt;linerange&gt; \n
              &lt;deleteline&gt;+
              --- \n
              &lt;appendline&gt;+
              { $appendline =~ s/ &lt;in_marker&gt; /&lt;/;
                $deleteline =~ s/ &lt;out_marker&gt; /&gt;/;
                let $0 := &quot;${to}c${from}\n&quot;
                        _ join(&quot;&quot;, @$appendline)
                        _ &quot;---\n&quot;
                        _ join(&quot;&quot;, @$deleteline);
              }
            ]
          |
            &lt;badline(&quot;Invalid diff hunk&quot;)&gt;
        }
    }</pre>
<p>The <code>ReverseDiff is Diff</code> syntax is the standard Perl 6 way of
inheriting behaviour. Classes will use the same notation:</p>
<pre>        class Hacker is Programmer {...}
        class JAPH is Hacker {...}
        # etc.</pre>
<p>Likewise, in the above example Diff is specified as the base grammar
from which the new ReverseDiff grammar is derived. As a result of that
inheritance relationship, ReverseDiff immediately inherits all of the
Diff grammar's rules. We then simple redefine ReverseDiff's version of
the <code>hunk</code> rule, and the job's done.</p>
<a name='Different diffs'></a><h1>Different diffs</h1>
<p>Grammatical inheritance isn't only useful for tweaking the behaviour of
a grammar's rules. It's also handy when two or more related grammars
share some characteristics, but differ in some particulars. For example,
suppose we wanted to support the &quot;unified&quot; diff format, as well as the
&quot;classic&quot;.</p>
<p>A unified diff consists of two lines of header information, followed by
a series of hunks. The header information indicates the name and
modification date of the old file (prefixing the line with three minus
signs), and then the name and modification date of the new file
(prefixing that line with three plus signs). Each hunk consists of an
offset line, followed by one or more lines representing either shared
context, or a line to be inserted, or a line to be deleted. Offset lines
start with two &quot;at&quot; signs, then consist of a minus sign followed by the
old line offset and line-count, and then a plus sign followed by the
new line offset and line-count, and then two more &quot;at&quot; signs. Context
lines are prefixed with two spaces. Insertion lines are prefixed with a
plus sign and a space. Deletion lines are prefixed with a minus sign
and a space.</p>
<p>But that's not important right now.</p>
<p>What <i>is</i> important is that we could write another complete grammar for
that, like so:</p>
<pre>    grammar Diff::Unified {

        rule file { ^  &lt;fileinfo&gt;  &lt;hunk&gt;*  $ }

        rule fileinfo {
                &lt;out_marker&gt;&lt;3&gt; $oldfile:=(\S+) $olddate:=[\h* (\N+?) \h*?] \n</pre>
<p>[Update: The generalized repetition is now <code>**{$n..$m}</code>, and the braces may be
omitted for literal numbers, so that <code>&lt;out_marker&gt;&lt;3&gt;</code>
would now be written <code>&lt;out_marker&gt; ** 3</code>.]</p>
<pre>                &lt;in_marker&gt;&lt;3&gt;  $newfile:=(\S+) $newdate:=[\h* (\N+?) \h*?] \n
        }

        rule hunk { 
            &lt;header&gt;
            @spec := ( &lt;contextline&gt;
                     | &lt;appendline&gt;
                     | &lt;deleteline&gt;
                     | &lt;badline(&quot;Invalid line for unified diff&quot;)&gt;
                     )*
        }

        rule header {
            \@\@ &lt;out_marker&gt; &lt;linenum&gt; , &lt;linecount&gt; \h+
                 &lt;in_marker&gt;  &lt;linenum&gt; , &lt;linecount&gt; \h+
            \@\@ \h* \n
        }

        rule badline ($errmsg) { (\N*) ::: { fail &quot;$errmsg: $1&quot; } }

        rule linenum   { (\d+) }
        rule linecount { (\d+) }

        rule deleteline  { ^^ &lt;out_marker&gt; (\N* \n) }
        rule appendline  { ^^ &lt;in_marker&gt;  (\N* \n) }
        rule contextline { ^^ &lt;sp&gt; &lt;sp&gt;    (\N* \n) }

        rule out_marker { \+ &lt;sp&gt; }
        rule in_marker  {  - &lt;sp&gt; }
    }</pre>
<p>That represents (and can parse) the new diff format correctly,
but it's a needless duplication of effort and code. Many the rules of
this grammar are identical to those of the original diff parser. Which
suggests we could just grab them straight from the original -- by
inheriting them:</p>
<pre>    grammar Diff::Unified is Diff  {

        rule file { ^  &lt;fileinfo&gt;  &lt;hunk&gt;*  $ }

        rule fileinfo {
                &lt;out_marker&gt;&lt;3&gt; $newfile:=(\S+) $olddate:=[\h* (\N+?) \h*?] \n
                &lt;in_marker&gt;&lt;3&gt;  $newfile:=(\S+) $newdate:=[\h* (\N+?) \h*?] \n
        }

        rule hunk { 
            &lt;header&gt;
            @spec := ( &lt;contextline&gt;
                     | &lt;appendline&gt;
                     | &lt;deleteline&gt;
                     | &lt;badline(&quot;Invalid line for unified diff&quot;)&gt;
                     )*
        }

        rule header {
            \@\@ &lt;out_marker&gt; &lt;linenum&gt; , &lt;linecount&gt; \h+
                 &lt;in_marker&gt;  &lt;linenum&gt; , &lt;linecount&gt; \h+
            \@\@ \h* \n
        }

        rule linecount { (\d+) }

        rule contextline { ^^ &lt;sp&gt; &lt;sp&gt;  (\N* \n) }

        rule out_marker { \+ &lt;sp&gt; }
        rule in_marker  {  - &lt;sp&gt; }
    }</pre>
<p>Note that in this version we don't need to specify the rules for
<code>appendline</code>, <code>deleteline</code>, <code>linenum</code>, etc. They're provided
automagically by inheriting from the <code>Diff</code> grammar. So we only have to
specify the parts of the new grammar that differ from the original.</p>
<p>In particular, this is where we finally reap the reward for factoring
out the <code>in_marker</code> and <code>out_marker</code> rules. Because we did that
earlier, we can now just change the rules for matching those two markers
directly in the new grammar. As a result, the inherited <code>appendline</code> and
<code>deleteline</code> rules (which use <code>in_marker</code> and <code>out_marker</code> as
subrules) will now attempt to match the new versions of <code>in_marker</code> and
<code>out_marker</code> rules instead.</p>
<p>And if you're thinking that looks suspiciously like polymorphism, you're
absolutely right. The parallels between pattern matching and OO run
<i>very</i> deep in Perl 6.</p>
<a name='Let's get cooking'></a><h1>Let's get cooking</h1>
<p>To sum up: Perl 6 patterns and grammars extend Perl's text matching
capacities enormously. But you don't have to start using all that extra
power right away. You can ignore grammars and embedded closures and
assertions and the other sophisticated bits until you actually need them.</p>
<p>The new rule syntax also cleans up much of the &quot;line-noise&quot; of Perl 5
regexes. But the fundamentals don't change that much. Many Perl 5
patterns will translate very simply and naturally to Perl 6.</p>
<p>To demonstrate that, and to round out this exploration of Perl 6
patterns, here are a few common Perl 5 regexes -- some borrowed from
the <i>Perl Cookbook</i>, and others from the Regexp::Common module --
all ported to equivalent Perl 6 rules:</p>
<ul>
<li><a name='Match a C comment:'></a>Match a C comment:</li>
<pre>        # Perl 5
        $str =~ m{ /\* .*? \*/ }xs;

        # Perl 6
        $str =~ m{ /\* .*? \*/ };</pre>
<p>[Update: Use <code>~~</code> now.]</p>
<li><a name='Remove leading qualifiers from a Perl identifier'></a>Remove leading qualifiers from a Perl identifier</li>
<pre>        # Perl 5
        $ident =~ s/^(?:\w*::)*//;

        # Perl 6
        $ident =~ s/^[\w*\:\:]*//;</pre>
<li><a name='Warn of text with lines greater than 80 characters'></a>Warn of text with lines greater than 80 characters</li>
<pre>        # Perl 5
        warn &quot;Thar she blows!: $&amp;&quot;
                if $str =~ m/.{81,}/;


        # Perl 6
        warn &quot;Thar she blows!: $0&quot;
                if $str =~ m/\N&lt;81,&gt;/;</pre>
<p>[Update:</p>
<pre>        warn &quot;Thar she blows!: $()&quot;
                if $str ~~ m/ \N ** 81..* /;</pre>
<p>]</p>
<li><a name='Match a Roman numeral'></a>Match a Roman numeral</li>
<pre>        # Perl 5
        $str =~ m/ ^ m* (?:d?c{0,3}|c[dm]) (?:l?x{0,3}|x[lc]) (?:v?i{0,3}|i[vx]) $ /ix;

        # Perl 6
        $str =~ m:i/ ^ m* [d?c&lt;0,3&gt;|c&lt;[dm]&gt;] [l?x&lt;0,3&gt;|x&lt;[lc]&gt;] [v?i&lt;0,3&gt;|i&lt;[vx]&gt;] $ /;</pre>
<p>[Update: Now <code>c ** 0..3</code> etc.]</p>
<li><a name='Extract lines regardless of line terminator'></a>Extract lines regardless of line terminator</li>
<pre>        # Perl 5
        push @lines, $1
                while $str =~ m/\G([^\012\015]*)(?:\012\015?|\015\012?)/gc;

        # Perl 6
        push @lines, $1
                while $str =~ m:c/ (\N*) \n /;</pre>
<li><a name='Match a quote-delimited string (Friedl-style), capturing contents:'></a>Match a quote-delimited string (Friedl-style), capturing contents:</li>
<pre>        # Perl 5
        $str =~ m/ &quot; ( [^\\&quot;]* (?: \\. [^\\&quot;]* )* ) &quot; /x;

        # Perl 6
        $str =~ m/ &quot; ( &lt;-[\\&quot;]&gt;* [ \\. &lt;-[\\&quot;]&gt;* ]* ) &quot; /;</pre>
<li><a name='Match a decimal IPv4 address:'></a>Match a decimal IPv4 address:</li>
<pre>        # Perl 5
        my $quad = qr/(?: 25[0-5] | 2[0-4]\d | [0-1]??\d{1,2} )/x;

        $str =~ m/ $quad \. $quad \. $quad \. $quad /x;


        # Perl 6
        rule quad {  (\d&lt;1,3&gt;) :: { fail unless $1 &lt; 256 }  }

        $str =~ m/ &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; /;


        # Perl 6 (same great approach, now less syntax)
        rule quad {  (\d&lt;1,3&gt;) :: &lt;($1 &lt; 256)&gt;  }

        $str =~ m/ &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; /;</pre>
<p>[Update: Now written:</p>
<pre>        token quad {  (\d**1..3) &lt;?{ $1 &lt; 256 }&gt;  }
        $str ~~ m/ &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; &lt;dot&gt; &lt;quad&gt; /;</pre>
<p>]</p>
<li><a name='Match a floating-point number, returning components:'></a>Match a floating-point number, returning components:</li>
<pre>        # Perl 5
        ($sign, $mantissa, $exponent) =
                $str =~ m/([+-]?)([0-9]+\.?[0-9]*|\.[0-9]+)(?:e([+-]?[0-9]+))?/;


        # Perl 6
        ($sign, $mantissa, $exponent) =
                $str =~ m/(&lt;[+-]&gt;?)(&lt;[0-9]&gt;+\.?&lt;[0-9]&gt;*|\.&lt;[0-9]&gt;+)[e(&lt;[+-]&gt;?&lt;[0-9]&gt;+)]?/;</pre>
<li><a name='Match a floating-point number maintainably, returning components:'></a>Match a floating-point number <i>maintainably</i>, returning components:</li>
<pre>        # Perl 5
        my $digit    = qr/[0-9]/;
        my $sign_pat = qr/(?: [+-]? )/x;
        my $mant_pat = qr/(?: $digit+ \.? $digit* | \. digit+ )/x;
        my $expo_pat = qr/(?: $signpat $digit+ )? /x;

        ($sign, $mantissa, $exponent) =
                $str =~ m/ ($sign_pat) ($mant_pat) (?: e ($expo_pat) )? /x;


        # Perl 6
        rule sign     { &lt;[+-]&gt;? }
        rule mantissa { &lt;digit&gt;+ [\. &lt;digit&gt;*] | \. &lt;digit&gt;+ }
        rule exponent { [ &lt;sign&gt; &lt;digit&gt;+ ]? }

        ($sign, $mantissa, $exponent) = 
                $str =~ m/ (&lt;sign&gt;) (&lt;mantissa&gt;) [e (&lt;exponent&gt;)]? /;</pre>
<li><a name='Match nested parentheses:'></a>Match nested parentheses:</li>
<pre>        # Perl 5
        our $parens = qr/ \(  (?: (?&gt;[^()]+) | (??{$parens}) )*  \) /x;
        $str =~ m/$parens/;


        # Perl 6
        $str =~ m/ \(  [ &lt;-[()]&gt; + : | &lt;self&gt; ]*  \) /;</pre>
<li><a name='Match nested parentheses maintainably:'></a>Match nested parentheses <i>maintainably</i>:</li>
<pre>        # Perl 5
        our $parens = qr/
                   \(                   # Match a literal '('
                   (?:                  # Start a non-capturing group
                       (?&gt;              #     Never backtrack through...
                           [^()] +      #         Match a non-paren (repeatedly)
                       )                #     End of non-backtracking region
                   |                    # Or
                       (??{$parens})    #    Recursively match entire pattern
                   )*                   # Close group and match repeatedly
                   \)                   # Match a literal ')'
                 /x;

        $str =~ m/$parens/;


        # Perl 6
        $str =~ m/ &lt;'('&gt;                # Match a literal '('
                   [                    # Start a non-capturing group
                        &lt;-[()]&gt; +       #    Match a non-paren (repeatedly)
                        :               #    ...and never backtrack that match
                   |                    # Or
                        &lt;self&gt;          #    Recursively match entire pattern
                   ]*                   # Close group and match repeatedly
                   &lt;')'&gt;                # Match a literal ')'
                 /;</pre>
</ul>
</div>
